package com.elitel.frame.base.component.quartz;


import com.elitel.common.quartz.AdaptableJobFactory;
import org.quartz.Scheduler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import javax.xml.crypto.Data;

/**
 * Quartz配置类
 * created by guoyanfei on 2018/4/26
 */
@Configuration
public class QuartzConfig {
    @Autowired
    private AdaptableJobFactory adaptableJobFactory;

    @Autowired
    @Qualifier("primaryDataSource")
    DataSource primaryDataSource;

    // 配置文件路径
    private static final String QUARTZ_CONFIG = "quartz.properties";

    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(){
        SchedulerFactoryBean schedulerFactoryBean = new SchedulerFactoryBean();
        /**
         * 启动时，更新已存在的Job,这样就不用每次修改targetObject后<br/>
         * 删除qrtz_job_details表对应记录了
         */
        schedulerFactoryBean.setOverwriteExistingJobs(true);
        //延迟10秒启动
        schedulerFactoryBean.setStartupDelay(10);
        // 直接使用配置文件,用于quartz集群,加载quartz数据源配置
        schedulerFactoryBean.setConfigLocation(new ClassPathResource(QUARTZ_CONFIG));
        //单机模式下关闭，集群模式下开启
//        schedulerFactoryBean.setDataSource(primaryDataSource);
        schedulerFactoryBean.setApplicationContextSchedulerContextKey("applicationContextKey");
        schedulerFactoryBean.setAutoStartup(true);
        //把JobFactory改成自定义的，并注入到spring容器
        schedulerFactoryBean.setJobFactory(adaptableJobFactory);

        return schedulerFactoryBean;
    }

    @Bean
    public Scheduler scheduler(){
        return schedulerFactoryBean().getScheduler();
    }

}
